<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '200px'" class="aside">
      <div class="logo-container">
        <div class="logo-box">
          <img src="@/assets/images/logo.png" alt="Logo" class="logo-image" />
        </div>
        <span v-show="!isCollapse" class="logo-text">{{ systemStore.systemConfig.backendName || '证书管理系统' }}</span>
      </div>
      <el-menu
        :collapse="isCollapse"
        :collapse-transition="false"
        :default-active="activeMenu"
        class="menu"
        router
      >
        <template v-for="menu in menus" :key="menu.path">
          <el-menu-item 
            v-for="item in menu.children" 
            :key="item.path"
            :index="`/admin/${item.path}`"
          >
            <el-icon>
              <component :is="iconMap[item.meta.icon]" />
            </el-icon>
            <span>{{ item.meta.title }}</span>
          </el-menu-item>
        </template>
      </el-menu>
      <div class="menu-divider"></div>
      <div class="menu-bottom">
        <a href="https://gitee.com/ztzjx/querysystem/tree/pro/" target="_blank" class="update-link">
          <div class="left-content">
            <el-icon><RefreshRight /></el-icon>
            <span>检查更新</span>
          </div>
          <span class="version-text">{{ VERSION.number }}</span>
        </a>
      </div>
    </el-aside>
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <el-icon class="toggle-sidebar" @click="toggleSidebar">
            <Fold v-if="!collapsed" />
            <Expand v-else />
          </el-icon>
        </div>
        <div class="header-right">
          <el-button type="danger" link @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-header>
      <el-main class="main">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useSystemStore } from '@/stores/system'
import menus from '@/router/menu'
import { VERSION } from '@/config/version'
import {
  Document,
  List,
  Key,
  SwitchButton,
  Fold,
  Expand,
  DataLine,
  RefreshRight,
  Setting,
  Menu,
  OfficeBuilding,
  User
} from '@element-plus/icons-vue'
import { ElMessageBox, ElLoading } from 'element-plus'

const _router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const systemStore = useSystemStore()
const collapsed = ref(false)
const isCollapse = ref(window.innerWidth <= 768)

const toggleSidebar = () => {
  collapsed.value = !collapsed.value
}

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      userStore.logout()
    })
    .catch(() => {
      // 取消退出
    })
}

window.addEventListener('resize', () => {
  isCollapse.value = window.innerWidth <= 768
})

const activeMenu = computed(() => {
  return route.path
})

// 检查更新
const handleCheckUpdate = async () => {
  try {
    const res = await fetch('/api/system/check-update')
    const data = await res.json()

    if (data.hasUpdate) {
      try {
        const confirm = await ElMessageBox.confirm(
          `发现新版本 ${data.latestVersion}\n\n` +
            `发布日期：${data.releaseDate}\n\n` +
            `更新内容：\n${data.description}`,
          '系统更新',
          {
            confirmButtonText: '立即更新',
            cancelButtonText: '暂不更新',
            type: 'info'
          }
        )

        if (confirm) {
          // 显示更新中的loading
          const loading = ElLoading.service({
            lock: true,
            text: '正在更新...',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          try {
            const updateRes = await fetch('/api/system/do-update', {
              method: 'POST'
            })
            const updateData = await updateRes.json()

            loading.close()

            if (updateData.success) {
              await ElMessageBox.alert(updateData.message, '更新成功', {
                type: 'success',
                confirmButtonText: '确定'
              })
            } else {
              throw new Error(updateData.error)
            }
          } catch (error) {
            loading.close()
            ElMessageBox.alert(error.message || '更新失败，请稍后重试', '更新失败', {
              type: 'error',
              confirmButtonText: '确定'
            })
          }
        }
      } catch {
        // 用户点击取消，不做任何操作
      }
    } else {
      ElMessageBox.alert(data.message, '系统更新', {
        confirmButtonText: '确定',
        type: 'success'
      })
    }
  } catch (error) {
    ElMessageBox.alert('检查更新失败，请稍后重试', '系统更新', {
      confirmButtonText: '确定',
      type: 'error'
    })
  }
}

const iconMap = {
  Document,
  List,
  Key,
  DataLine,
  Setting,
  Menu,
  OfficeBuilding,
  User
}

onMounted(() => {
  systemStore.fetchSystemConfig()
  
  // 监听系统Logo更新事件
  window.addEventListener('system-logo-updated', (event) => {
    const logoUrl = event.detail
    if (logoUrl) {
      // 更新logo并强制刷新
      const logoImg = document.querySelector('.logo-image')
      if (logoImg) {
        // 先清除旧的src
        logoImg.src = ''
        // 强制重新加载
        setTimeout(() => {
          logoImg.src = logoUrl
        }, 50)
      }
    }
  })
})

// 确保在组件销毁时移除事件监听
onUnmounted(() => {
  window.removeEventListener('system-logo-updated', () => {})
})
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
}

.aside {
  background-color: #fff;
  border-right: 1px solid #e2e8f0;
  transition: width 0.3s;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

.logo-container {
  display: flex;
  align-items: center;
  height: 56px;
  padding: 0 20px;
  overflow: hidden;
  background: var(--el-menu-bg-color);
  border-bottom: 1px solid #e2e8f0;
}

.logo-container .logo {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.logo-container .title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.logo-box {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  overflow: hidden;
  background: #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.logo-image {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.logo-text {
  margin-left: 10px;
  font-size: 15px;
  font-weight: 500;
  color: #1e293b;
  white-space: nowrap;
}

.menu {
  border-right: none;
  width: 100%;
  padding: 12px 0;
  flex: 1;
  height: calc(100% - 120px);
  overflow-y: auto;
}

.menu :deep(.el-menu-item) {
  padding: 0 20px !important;
  height: 48px;
  line-height: 48px;
  margin: 4px 0;
}

.menu :deep(.el-menu-item .el-icon) {
  margin-right: 12px;
  font-size: 16px;
}

.menu :deep(.el-menu-item.is-active) {
  background-color: #eff6ff;
  color: #3b82f6;
  font-weight: 500;
}

.menu :deep(.el-menu-item:hover) {
  background-color: #f8fafc;
}

.menu-divider {
  height: 1px;
  background-color: #e2e8f0;
  margin: 0;
}

.menu-bottom {
  height: 54px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  border-top: 1px solid #e2e8f0;

  .update-link {
    display: flex;
    align-items: center;
    color: var(--el-color-primary);
    text-decoration: none;
    font-size: 14px;
    padding: 8px 12px;
    border-radius: 4px;
    transition: all 0.3s;
    width: 100%;

    .version-text {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-left: auto;
      padding-left: 8px;
    }

    .left-content {
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        font-size: 16px;
      }
    }

    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 20px;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  height: 32px;
  padding: 0 12px;
}

.header-right .el-button:hover {
  background-color: #fef0f0;
}

.toggle-sidebar {
  font-size: 20px;
  cursor: pointer;
  color: #606266;
}

.toggle-sidebar:hover {
  color: var(--el-color-primary);
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #606266;
}

.main {
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #fff;
  min-height: calc(100vh - 56px);

  :deep(.el-card) {
    margin: 0;
    border: none;
    box-shadow: none;
    height: 100%;
  }

  :deep(.el-card__header) {
    padding: 0;
    border-bottom: 1px solid #e2e8f0;
  }

  :deep(.el-card__body) {
    padding: 16px;
    height: calc(100% - 56px);
    overflow-y: auto;
  }
}

.fade-enter-active,
.fade-leave-active,
.fade-enter-from,
.fade-leave-to {
  display: none;
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .aside {
    width: 64px !important;
  }

  .logo-container {
    padding: 0 16px;
    justify-content: center;
  }

  .logo-container .title {
    display: none;
  }

  .main {
    padding: 0;
  }

  .main :deep(.el-card) {
    border-radius: 0;
  }

  .menu-bottom {
    height: 48px;
    padding: 0 8px;

    .update-link {
      padding: 8px;
      justify-content: center;
      gap: 4px;
      
      .left-content span {
        display: none;
      }

      .version-text {
        margin-left: 4px;
      }
    }
  }
}
</style>
